package com.example.webjsapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private WebView contentWebView = null;
    private TextView msgView = null;

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contentWebView =  findViewById(R.id.webview);
        msgView =  findViewById(R.id.msg);
        // 启用javascript
        contentWebView.getSettings().setJavaScriptEnabled(true);
        // 从assets目录下面的加载html
        contentWebView.loadUrl("file:///android_asset/wst.html");

        contentWebView.addJavascriptInterface(new MyJavascriptInterface(), "wifikeyJsBridge");
    }


    public class MyJavascriptInterface {

        @JavascriptInterface
        public void startFunction() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("rzx","1231312321");

                }
            });
        }

        @JavascriptInterface
        public void startFunction(final String str) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("rzx","1231312321");
                }
            });
        }

        @JavascriptInterface
        public void call(final String str) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONArray jSONArray;
                    JSONArray jSONArray2;

                    JSONObject jSONObject3 = null;
                    try {
                        jSONObject3 = new JSONObject(str);
                        String string = jSONObject3.getString("method");
                        jSONArray = jSONObject3.getJSONArray("types");
                        jSONArray2 = jSONObject3.getJSONArray("args");
                        String optString = jSONArray.optString(0);
                        Log.e("rzx",optString);
                    } catch (JSONException e) {
                        if (e.getCause() != null) {
                            Log.e("rzx", e.getCause().getMessage());
                        }else{
                            Log.e("rzx", e.getMessage());

                        }
                    }

                }
            });
        }


    }
}